package com.shopx.base.utils;

import com.shopx.base.dto.Result;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.ShopxException;
import com.shopx.core.DTO.ExcelObjectDTO;
import com.shopx.core.utils.DateTimeUtil;
import com.shopx.core.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author lituo
 * @version 1.0
 * @descript TODO
 * @date 2021/11/18 9:39
 */
@Slf4j
public class ResultUtil {
  public static Result ok() {
    return ok(null);
  }

  public static Result ok(Object object) {
    return new Result(ResultCodeEnum.SUCCESS.value(),
        ResultCodeEnum.SUCCESS.message(), object);
  }

  public static Result fail(ResultCodeEnum resultCodeEnum) {
    return new Result(resultCodeEnum.value(), resultCodeEnum.message(), null);
  }

  public static Result fail(String code, String message) {
    return new Result(code, message, null);
  }

  public static Result fail(ResultCodeEnum resultCodeEnum, String message) {
    return new Result(resultCodeEnum.value(), StringUtils.isBlank(message) ? resultCodeEnum.message() : message, null);
  }

  /**
   * excel下载
   *
   * @param dto
   * @param response
   * @return void
   * @author lituo
   * @date 4:07 PM 2022/2/27
   */
  public static void excelDownload(ExcelObjectDTO dto, HttpServletResponse response) {
    HSSFWorkbook wb = null;
    OutputStream os = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      byte[] ba = baos.toByteArray();
      wb = ExcelUtil.generatorExcel(dto);
      os = response.getOutputStream();
      baos.flush();
      wb.write(baos);

      ba = baos.toByteArray();
      response.reset();// 重置response
      response.setContentType("text/html;charset=UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename=" + DateTimeUtil.getDateTime14() + ".xlsx");
      response.setContentType("application/x-msdownload");
      os.write(ba);// 导出
    } catch (Exception e) {
      log.info("download.error", e);
      throw new ShopxException(ResultCodeEnum.EXPORT_ERROR);
    } finally {
      if (null != baos) {
        try {
          baos.close();
        } catch (IOException e) {
          log.info("baos.close.error", e);
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (IOException e) {
          log.info("os.close.error", e);
        }

      }
      if (response != null) {
        try {
          response.getWriter().close();
        } catch (IOException e) {
          log.info("response.close.error", e);
        }
      }
    }
  }
}
